package com.example.zhuma.utill;
import android.os.Handler;


import com.example.zhuma.MonitorActivity;
import com.example.zhuma.entity.Message;
import com.google.gson.Gson;

import java.io.*;
import java.net.Socket;

public class ClientSocket {

    private Socket socket;
    public static final String HOST = "192.168.179.1";
    public static final int PORT = 9527;
    public ClientSocket() throws IOException {
        socket = new Socket(HOST,PORT);
    }

    public void sendMessage(String s) throws IOException {
//        BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//        bf.write(s);
//        bf.flush();
        PrintWriter pw = new PrintWriter(socket.getOutputStream());
        pw.println(s);
        pw.flush();
    }

    public void sendMessages() throws IOException {
        while (true){
            String message = readMessageByKeyBoard();
            sendMessage(message);
        }
    }


    /**
     * 从键盘读消息发送
     * @throws IOException
     */
    public String readMessageByKeyBoard() throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String s =  bufferedReader.readLine();
        return s;
    }

    /*
     * 读消息
     */
    public String readMessage() throws IOException {
        String line = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        line = br.readLine();
        return line;

    }

    /**
     * 循环读取消息
     * @throws IOException
     */
    public void cycleReadMessage() throws IOException {
        while (true){
            String message = readMessage();
            if (message!=null){
                System.out.println("服务器端:"+message);
            }
        }
    }
    public void resolveMessage(String message)
    {
        Gson gson = new Gson();
        Message ms = gson.fromJson(message, Message.class);

        switch (ms.getType())
        {
            case MA_VIDEO:resolveVideo(message, MonitorActivity.mHandler);
        }
    }
    public void resolveVideo(String ms, Handler mHandler)
    {
        android.os.Message msg =new android.os.Message();

        msg.obj =ms;
        mHandler.sendMessage(msg);
    }
    public void close() throws IOException {
        if(socket!=null)
        {
            socket.close();
        }
    }

}

